<?php
namespace Base\Controller;

use Library\Chart;
use Library\Encrypt;
use Library\UploadFile;
use Think\Controller\RestController;

class BaseApiController extends RestController
{
    protected $table; //表名
    protected $model; //模型
    protected $relation;//关联

    public function __construct($relation = false)
    {
        parent::__construct();
        if (empty($this->table)){
            $this->table = hump2underline(CONTROLLER_NAME);//获取当前控制器对应的表名
        }
        $this->relation = $relation;
        $this->initModel();
    }

    /**
     * 初始化模型
     */
    protected function initModel()
    {
        if ($this->relation) {
            $this->model = D($this->table)->relation($this->relation);
        } else {
            $this->model = M($this->table);
        }
    }
    /**
     * @param string $data
     * 成功返回
     * @param string $msg
     */
    protected function apiSuccess($data, $msg = '')
    {
        $this->response(array(
            'data' => $data,
            'msg' => $msg,
            'code' => 1,
        ),'json');
        exit();
    }

    /**
     * @param string $msg
     * @param int $code
     * 错误返回
     */
    protected function apiError($msg = '',$code = 0)
    {
        $this->response(array(
            'data' => null,
            'msg' => $msg,
            'code' => $code,
        ),'json');
        exit();
    }

    /**
     * 查询返回
     */
    protected function apiReturn($data){
        if (empty($data)){
            $this->apiError('暂无数据');
        }else{
            $this->apiSuccess($data,'查询成功');
        }
    }

    /**
     * 查询信息列表
     */
    public function getList(){

        $data = $this->model->where(array('status'=>1))->select();
        $this->apiReturn($data);
    }

    /**
     * @param bool $is_msg
     * @param string $patient_id
     * 检测患者token是否有效
     */
//    public function checkPatientToken($is_msg = true,$patient_id = ''){
//        $patient_id = empty($patient_id) ? I('post.patient_id') : $patient_id; //患者id
//        $token = I('post.token');  //令牌
//        if(empty($patient_id) || empty($token)){
//            $this->apiError('患者用户id或者token不能为空！');
//        }
//        $pModel = new PatientModel();
//        $data = $pModel->where(array('id'=>$patient_id,'token'=>$token,'status'=>1))->getField('id');
//        if (empty($data)){
//            session('user_id',null);
//            session('user_type',null);
//            $this->apiError('token已失效',-1);
//        }else{
//            session('user_id',$patient_id);
//            session('user_type',1);
//            if ($is_msg){
//                $this->apiSuccess($data,'token有效');
//            }
//        }
//    }
//
//    /**
//     * @param bool $is_msg
//     * @param string $doctor_id
//     * 检测医生token是否有效
//     */
//    public function checkDocToken($is_msg = true,$doctor_id = ''){
//        $doctor_id = empty($doctor_id) ? I('post.doctor_id') : $doctor_id;  //医生id
//        $token = I('post.token');   //令牌
//        if(empty($doctor_id)||empty($token)){
//            $this->apiError('医生用户id或者token不能为空！');
//        }
//        $docModel = new DoctorModel();
//        $data = $docModel->where(array('id'=>$doctor_id,'token'=>$token,'status'=>1))->field('id,reviewed')->find();
//        if (empty($data)){
//            session('user_id',null);
//            session('user_type',null);
//            $this->apiError('token已失效',-1);
//        }else{
//            session('user_id',$doctor_id);
//            session('user_type',2);
//            //排除验证上产资格证接口
//            $is_upCer = false;
//            if (CONTROLLER_NAME=='Doctor' and ACTION_NAME=='upCertification'){
//                $is_upCer = true;
//            }
//            if ($data['reviewed'] != 1 and !$is_upCer){
//                $this->apiError('审核未通过');
//            }
//            if ($is_msg){
//                $this->apiSuccess($data,'token有效');
//            }
//        }
//    }

    /**
     * 获取分页
     */
    public function getPage(){
        //分页
        $page = I('post.page');
        $page = empty($page) ? 1 : $page;
        return $page;
    }

    //---------------上传图片----------------/
    /**
     * @param string $inputname
     * @return bool|string
     * 上传图片
     */
    protected function upImgFile($inputname='cover'){
        if ($_FILES[$inputname]){
            //上传图片
            $input_name = 'cover';
            $up = new UploadFile();
            $info = $up->upFile($input_name, array('jpg', 'png', 'jpeg'));
            if (empty($info)){
                return false;
            }else{
                $cover = $info[$inputname]['savepath'] . $info[$inputname]['savename'];
                return $cover;
            }
        }
    }

    /**
     * @param string $input_name
     * @return mixed
     * 上传多张图片
     */
    protected function upMoreImg($input_name='picture'){
        //上传多张图片
        $covers = $_FILES[$input_name];
        $type = false;
        if ($covers){
            //获取所有图片路径
            $names = $covers['name'];
        }else{
            $type = true;
            $covers = $_FILES[$input_name.'1'];
            for ($i=1;$i<=6;$i++){
                $inputName = $input_name.$i;
                $pFile = $_FILES[$inputName];
                if ($pFile){
                    $names[] = $pFile['name'];
                }
            }
        }
        if ($covers){
            $up = new UploadFile();
            $add = 0;
            if ($type){
                $info = $up->upDifferentImg($input_name);
            }
            foreach ($names as $k=>$v){
                if ($type){
                    $inpName = $input_name.($k+1);
                    $picture = $info[$inpName][$inpName];
                }else{
                    $info = $up->upDifferentImg($input_name);
                    $picture = $info[$input_name][$k];
                }
                $paths[] = $picture['savepath'].$picture['savename'];
            }
        }
        return $paths;
    }

    //json转数组
    protected function jsonToArr($data){
        if (!empty($data[0])){
            foreach ($data as $k=>$v){
                //医生主治疾病
                $disease_id = json_decode($v['disease_id']);
                if (is_array($disease_id)){
                    //主治疾病json转数组
                    $data[$k]['disease_id'] = $disease_id;
                }
                $visit_time = json_decode($v['visit_time']);
                if (is_array($visit_time)){
                    //坐诊时间json转数组
                    $data[$k]['visit_time'] = $visit_time;
                }
            }
        }else{
            //医生主治疾病
            $disease_id = json_decode($data['disease_id']);
            if (is_array($disease_id)){
                //主治疾病json转数组
                $data['disease_id'] = $disease_id;
            }
            $visit_time = json_decode($data['visit_time']);
            if (is_array($visit_time)){
                //坐诊时间json转数组
                $data['visit_time'] = $visit_time;
            }
        }
        return $data;
    }

    /**
     * @param string $pwd
     * 验证密码
     */
    protected function checkPwd($pwd='pwd'){
        //判断密码是否纯数字
//        if(is_numeric($_POST[$pwd]) and strlen($_POST[$pwd])<8){
//            $this->apiError('纯数字密码最少8位！');
//        }
        if(strlen($_POST[$pwd])<6){
            $this->apiError('密码最少6位！');
        }else{
            if (!preg_match("/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){5,15}$/",$_POST[$pwd]))
            {
                $this->apiError('密码格式不对！（密码必须以字母开头，长度在6-16位之间）');
            }
        }
    }
    /**
     * @param $data
     * @return mixed
     * 排除部分不能修改的字段
     */
    public function excludeField($data){
        //不能修改用户名
        if ($_POST['name']){
            unset($data['name']);
        }
        //不能修改密码
        if($_POST['pwd'] || empty($data['pwd'])){
            unset($data['pwd']);
        }
        //排除主治疾病
        if(empty($data['disease_id'])){
            unset($data['disease_id']);
        }
        //不能修改token
        if ($_POST['token']){
            unset($data['token']);
        }
        //不能修改手机号
        if($_POST['phone']){
            unset($data['phone']);
        }
        //不能修改审核
        if ($_POST['reviewed']){
            unset($data['reviewed']);
        }
        //不能修改真名
//        if ($_POST['true_name']){
//            unset($data['true_name']);
//        }
        //不能修改身份证
        if ($_POST['id_card']){
            unset($data['id_card']);
        }
        //不能修改状态（用户名修改状态）
        if ($_POST['state']){
            unset($data['state']);
        }
        return $data;
    }

    /**
     * @param $array
     * @return array
     * 去除数组重复元素
     */
    protected function a_array_unique($array)//写的比较好
    {
        $out = array();
        foreach ($array as $key=>$value) {
            if (!in_array($value, $out))
            {
                $out[$key] = $value;
            }
        }
        return $out;
    }

    /**
     * @param $dates
     * @return string
     * 转换时间格式
     */
    public function convertTime($dates){
        //转换时间
        if (is_array($dates)){
            foreach ($dates as $k => $v){
                $dates[$k] = $this->strToYmd($v);
            }
        }else{
            $dates = $this->strToYmd($dates);
        }
        return $dates;
    }

    //字符串转年月日
    public function strToYmd($str){
        if (strlen($str) == 8){
            $Y = substr($str,0,4);
            $m = substr($str,4,2);
            $d = substr($str,6,8);
            return "$Y-$m-$d";
        }else{
            return $str;
        }
    }
    /**
     * @param $user_id    ---用户id
     * @param $user_type  ---用户类型(1.患者，2.医生)
     * @param $title ---消息
     * @param $data  ---数据
     * @param $device  ---设备类型
     *保存用户消息
     */
//    protected function addMsg($user_id='',$user_type='',$title='',$data=array(),$device=''){
//        //添加消息
//        $msg_info = M('msg_manager')->where(array('controller'=>CONTROLLER_NAME,'action'=>ACTION_NAME,'is_push'=>1,'status'=>1))->field('title,describe')->find();
//        if (!empty($msg_info)){
//            //获取用户信息
//            $userInfo['user_id'] = empty($user_id) ? session('user_id') : $user_id;
//            $userInfo['user_type'] = empty($user_type) ? session('user_type') : $user_type;
//            //患者用户
////                if (!empty($_SESSION['patient_id'])){
////                    $userInfo = array('user_id'=>$_SESSION['patient_id'],'user_type'=>1);
////                }
////                //医生用户
////                if (!empty($_SESSION['doctor_id'])){
////                    $userInfo = array('user_id'=>$_SESSION['doctor_id'],'user_type'=>2);
////                }
//            $title = empty($title) ? $msg_info['title'] : $title;  //消息
////            $data = empty($data) ? '' : $data;   //数据
//            $data['controller'] = CONTROLLER_NAME;
//            $data['action'] = ACTION_NAME;
//            if (!empty($userInfo['user_id'])){
//                $userInfo['title'] = $title;
//                $userInfo['content'] = $msg_info['describe'];
//                $userInfo['msg_data'] = json_encode($data);
//                $msgModel = new MessageModel();
//                $msgModel->add($msgModel->create($userInfo));
//                //获取用户名
//                $jPush = new jPush();
//                $jPush->pushMsg($userInfo['user_id'],$userInfo['user_type'],
//                    array('controller'=>CONTROLLER_NAME,'action'=>ACTION_NAME),
//                    $title,$title,$data,$device);
//            }
//        }
//    }

    /**
     * @param $user
     * @return bool
     * 验证用户名是否以字母开头(4-12位)
     */
    protected function is_user_name($user)
    {
        if (preg_match("/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){3,11}$/",$user))
        {
            return true;
        } else
        {
            return false;
        }
    }

    /**
     * @param $pwd
     * @return bool
     * 验证密码只能为数字和字母的组合(4-20位)
     */
    protected function is_pwd($pwd)
    {
        if (preg_match("/^(w){4,20}$/",$pwd))
        {
            return true;
        } else
        {
            return false;
        }
    }

    /**
     * @param $name
     * @param $pwd
     * 注册环信用户
     */
    protected function registerUser($name,$pwd){
        $chart = new Chart();
        $chart->registerUser($name,$pwd);
    }

    /**
     * @param $username
     * @param $friend_name
     * @return mixed
     * 环信添加好友
     */
    protected function addFriend($username,$friend_name){
        $chart = new Chart();
        return $chart->addFriend($username,$friend_name);
    }

    /**
     * @param $username
     * @param $nick
     * @return mixed
     * 修改用户昵称
     */
    protected function editNickname($username,$nick){
        $chart = new Chart();
        return $chart->editNickname($username,$nick);
    }
    //加密
    public function jiami($pwd){
        $dencrypt = new Encrypt();
        $str = $dencrypt->dencrypt($pwd);
        return $str;
    }

    //解密
    public function jiemi($pwd){
        $dencrypt = new Encrypt();
        $str = $dencrypt->dencrypt($pwd,false);
        return $str;
    }

    //批量注册环信用户
//    function registerAllEaseMobUser(){
//        $data = $this->model->getAll();
//        foreach ($data as $k=>$v){
//            //批量注册环信用户
//            $chart_name = 'ysd'.$v['id'];
//            $chart_pwd = sha1('yishu123456');
//            $v['chart_name'] = $chart_name;
//            $v['chart_pwd'] = $chart_pwd;
//            $this->registerUser($chart_name,$chart_pwd);
//            $this->model->save($v);
//        }
//    }


}